package com.baimifan.renovation.manager;

import android.os.Handler;
import android.os.Message;

import com.baimifan.renovation.MyApplication;
import com.baimifan.renovation.model.TaskData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * Created by baimifan on 2017/07/04.
 */

public class TaskManager {
    private Handler mHandler;
    private ArrayList<TaskData> lists = new ArrayList<>();
    private String url = MyApplication.MAIN + "/index/index/rewu";

    public  ArrayList<TaskData> gettasks () {
        return  lists;
    }

    public TaskManager (Handler handler) {
        this.mHandler = handler;
    }

    public void getTask (String area) {
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("area", area);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                try {
                    if (result.getInt("status") == 200) {
                        JSONArray array = result.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject data = array.getJSONObject(i);
                            TaskData taskdata = new TaskData();
                            if (!data.isNull("start_time")) {
                                taskdata.setStartTime(data.getString("start_time"));
                            }
                            if (!data.isNull("rw_title")) {
                                taskdata.setTitle(data.getString("rw_title"));
                            }
                            if (!data.isNull("img")) {
                                taskdata.setImg(MyApplication.MAIN + data.getString("img"));
                            }
                            if (!data.isNull("rw_yj")) {
                                taskdata.setRwyj(data.getString("rw_yj"));
                            }
                            if (!data.isNull("id")) {
                                taskdata.setId(data.getInt("id"));
                            }
                            lists.add(taskdata);
                        }
                        Message msg = new Message();
                        msg.what = 4;
                        mHandler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
